"use strict";
const mvc = require('cosjs.mvc');
const cosjs = require('cosjs');

const _dbPool     = cosjs.pool;
const _redis      = mvc.library.require('redis');
const _mongodb    = mvc.library.require('mongodb');


//session
exports.cache = class cache extends _redis.hash {
    constructor(name,format){
        let redis = _dbPool.get("cache");
        if(!redis){
            throw new Error("redis cache empty")
        }
        let prefix = ['C',name].join('');
        let formatOpt = format ? mvc.format(format) : null;
        super(redis,prefix,formatOpt);
    }
}


exports.mongodb = class mongodb extends _mongodb {
    constructor(name,upsert){
        let mongo = _dbPool.get("mongodb");
        if(!mongo){
            throw new Error("mongodb empty")
        }
        let dbname = [mvc.config.get("dbname")||'gm','share'].join('-');
        super(mongo,dbname,name,upsert);
    }
}

////////////////////////////////branch//////////////////////////////////////

exports.branch = {};
//用户锁
exports.branch.locks = class branch_locks extends _redis.locks {
    constructor(branch,name,expire){
        let redis = _dbPool.get("cache");
        if(!redis){
            throw new Error("redis cache empty")
        }
        let prefix = ['L',branch,name].join('-');
        super(redis,prefix,expire);
    }
}

//手机验证码
exports.branch.vcode = class branch_vcode extends _redis.string {
    constructor(branch){
        let redis = _dbPool.get("cache");
        if(!redis){
            throw new Error("redis cache empty")
        }
        let prefix = ['V',branch].join('|');
        super(redis,prefix);
    }
}

//平台授权
exports.branch.token = class branch_token extends _redis.string {
    constructor(branch){
        let redis = _dbPool.get("cache");
        if(!redis){
            throw new Error("redis cache empty")
        }
        let prefix = ['T',branch].join('|');
        super(redis,prefix);
    }
}

//订单信息
exports.branch.order = class branch_payment extends _redis.string {
    constructor(branch){
        let redis = _dbPool.get("cache");
        if(!redis){
            throw new Error("redis cache empty")
        }
        let prefix = ['O',branch].join('|');
        super(redis,prefix);
    }
}

exports.branch.mongodb = class branch_mongodb extends _mongodb {
    constructor(branch,name,upsert){
        if(!branch){
            throw new Error("branch empty at[dbase branch.mongodb]")
        }
        let mongo = _dbPool.get("mongodb");
        if(!mongo){
            throw new Error("mongodb empty")
        }
        let dbname = [mvc.config.get("dbname")||'gm',branch].join("-");
        super(mongo,dbname,name,upsert);
    }
}